# -*- coding: utf-8 -*-
'''
Created on Apr 6, 2013

@author: LONG HOANG GIANG
'''
import sqlite3, os
import logging
from PyLib import raw

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S')

class SQLiteHelper():
    
    __connection = None
    __database = ''
    
    def __init__(self, database):
        database = raw(database)
        self.__database = database
    
    def open(self, delete=False):
        logging.debug("open database {0}".format(self.__database))
        if (delete and os.path.isfile(self.__database)):
            os.unlink(self.__database)
        parent = os.path.dirname(self.__database)
        if not parent in ['', '.'] and not os.path.exists(parent):
            os.makedirs(parent, 0777)
        self.__connection = sqlite3.connect(self.__database)
        
    def getCursor(self):
        c = self.__connection.cursor()
        return c
    
    def getAllTableName(self):
        c = self.getCursor()
        c.execute("SELECT tbl_name FROM sqlite_master WHERE type='table' AND name != 'sqlite_sequence'")
        tables = c.fetchall()
        c.close()
        return [table[0] for table in tables]
    
    def renameTable(self, currentName, newName):
        newName = newName.strip()
        currentName = currentName.strip()
        if (newName == currentName or (newName == '')):
            return
        c = self.getCursor()
        sql = '''ALTER TABLE {_table} RENAME TO {_newtable};'''.format(_table=currentName, _newtable=newName)
        c.execute(sql)
        c.close()
    
    def close(self):
        self.__connection.commit()
        self.__connection.close()